package cn.hhy.hrm.config;

import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.security.sasl.AuthenticationException;

public class SmsDaoAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    private AccountStatusUserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();

    public Authentication authenticate(Authentication authentication) {
        //1.检查Token是否支持SmsAuthToken
        if (!supports(authentication.getClass())) {
            return null;
        }
        //2.获取到SmsAuthFilter传过来的token
        SmsAuthToken authenticationToken = (SmsAuthToken) authentication;
        //3.根据手机号加载UserDetails
        UserDetails user = getUserDetailsService().loadUserByUsername(authenticationToken.getPrincipal().toString());

        //4.检查账户过期等
        if(user == null)throw new UsernameNotFoundException("用户没找到");
        userDetailsChecker.check(user);
        //5.登录成功，返回Token对象
        return new SmsAuthToken(user,"",user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsAuthToken.class.isAssignableFrom(authentication);
    }
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
    protected UserDetailsService getUserDetailsService() {
        return this.userDetailsService;
    }
}